<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoMessage.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';

class MessageBus {
	private $_messageDao;
	private $_userBus;
	
	public function __construct() {
		$this->_messageDao = new MessageDao();
		$this->_userBus = new UserBus();
	}
	
	public function addMessage($message) {
		$message->setContent($message->getContent());
		$message->setTitle(GeneralFunctions::stripString($message->getTitle()));
		$message->setReceiverId(GeneralFunctions::stripString($message->getReceiverId()));	
		$message->setCreatedDate($_SERVER['REQUEST_TIME']);
		
		$id = $this->_messageDao->addMessage($message);
		
		if ($id) {
			global $ubi_score;
			$this->_userBus->addScore($message->getSenderID(), $ubi_score['SEND_MESSAGE']);	
		}
		
		return $id;
	}
	
	public function getMessagesBySenderId($senderId) {
		return $this->_messageDao->getMessagesBySenderId($senderId);
	}

	public function getReadMessagesByReceiverId($receiverId, $page) {
		global $ubi;
		 
		$from = ($page - 1) * $ubi['MESSAGE']['MESSAGE_PER_PAGE'];
		$to = $from +  $ubi['MESSAGE']['MESSAGE_PER_PAGE'];
		
		return $this->_messageDao->getReadMessagesByReceiverId($receiverId, $from, $to);
	}
	
	public function getUnreadMessagesByReceiverId($receiverID) {
		return $this->_messageDao->getUnreadMessagesByReceiverId($receiverID);
	}
	
	public function countUnreadmessageByReceiverId($receiverID) {
		return $this->_messageDao->countUnreadmessageByReceiverId($receiverID);
	}
	
	public function countReadMessages($receiverID) {
		return $this->_messageDao->countReadMessages($receiverID);
	}
	
	public function getSenderOfMessages($arrMess) {
		$users = array();
				
		foreach ($arrMess as $mess) {
			if (!isset($users[$mess->getSenderID()])) {
				$users[$mess->getSenderID()] = $this->_userBus->getUser($mess->getSenderID());
			}
		}
		
		return $users;
	}
	
	public function readMessage($messID) {
		return $this->_messageDao->readMessage($messID);
	}
	
	public function deleteMessage($messID) {
		return $this->_messageDao->deleteMessage($messID);
	}
	
	public function getAllMessagesByReceiverId($receiverID) {
		return $this->_messageDao->getAllMessagesByReceiverId($receiverID);
	}
}
?>